package com.zixuan.gulicollege.msmservice.service.impl;

import com.zixuan.gulicollege.common_utils.HttpUtils;
import com.zixuan.gulicollege.common_utils.RandomUtils;
import com.zixuan.gulicollege.msmservice.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName MsmServiceImpl
 * @Author by zixuan
 * @Date 2021/5/18 9:50
 */

@Service
public class MsmServiceImpl implements MsmService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void getPhoneCode(String appCode, String host, String path, String method, String templateId, String expireAt, String phoneNum) {
        String isCode = redisTemplate.opsForValue().get("getPhoneCode" + phoneNum);
        if (!StringUtils.isEmpty(isCode)) {
            return;
        }
        try {

            Map<String, String> headers = new HashMap<>(2);
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appCode);
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String, String> querys = new HashMap<>(0);
            Map<String, String> bodys = new HashMap<>(3);

            // 随机验证码
            String code = RandomUtils.getSixBitRandom();

            // 设置验证码
            bodys.put("content", "code:" + code + ",expire_at:" + expireAt);
            bodys.put("phone_number", phoneNum);
            bodys.put("template_id", templateId);

            // 将验证码存储到Redis中，过期时间为5分钟
            redisTemplate
                    .opsForValue()
                    .set(
                            phoneNum,
                            code,
                            Integer.parseInt(expireAt),
                            TimeUnit.MINUTES
                    );
            HttpUtils.doPost(host, path, method, headers, querys, bodys);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
